package com.fart.filter;


import com.alibaba.fastjson.JSON;
import com.fart.common.BaseContext;
import com.fart.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/* 过滤器: 检查用户是否已经完成登录 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(
            ServletRequest request,
            ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        //1.获取http请求和响应对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //2.获取当前请求的URI路径
        String requestURI = req.getRequestURI();
        //log.info("获取到当前请求信息:" + requestURI);

        //定义不需要处理的请求路径
        String[] res = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**"
        };

        //判断当前请求是否需要进行处理
        boolean check = isCheck(res, requestURI);

        //如果不需要处理,则直接放行
        if (check){
            //log.info("不需要处理的信息",requestURI);

            chain.doFilter(req,resp);
            return;
        }

        //如果是已登录状态,则直接放行
        if (req.getSession().getAttribute("employee") != null){
            //log.info("用户时已登录状态",req.getSession().getAttribute("employee"));
            long id = Thread.currentThread().getId();
            log.info("线程id:{}",id);
            Long empId = (Long)req.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(empId);
            chain.doFilter(req,resp);
            return;
        }

        //log.info("用户未登录");
        //用户未登录,则直接响应数据
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /* 用于判断当前路径是否需要进行放行 */
    private boolean isCheck(String[] urls,String requestURL){
        //urls: 不需要处理的请求路径
        for ( String url : urls) {
            //是否包含requestURL,当前请求
            boolean match = PATH_MATCHER.match(url, requestURL);
            if(match){
                return true;
            }
        }
        return false;
    }


}
